package cn.ssms.service;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import cn.ssms.dao.ImageMapper;
import cn.ssms.model.Image;
import cn.ssms.qiniu.NetUploadDemo;
import cn.ssms.util.ReqParams;

/**
 * 图片服务业务层
 * @author Administrator
 *
 */
@Service("imageUploadServiceImpl")
public class ImageUploadServiceImpl implements ImageUploadService {
	//设置好账号的ACCESS_KEY和SECRET_KEY
	String ACCESS_KEY = ReqParams.ACCESS_KEY;
	String SECRET_KEY = ReqParams.SECRET_KEY;
	@Autowired
	private ImageMapper imageMapper;
	@Override
	public boolean addImage(Image img) {
		try {
			int i = imageMapper.addImage(img);
			if(i>0){
				System.out.println("添加的i:"+i);
				return true;
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}
	public void updateImage(Image imageNewUrl) {
		imageMapper.updateImage(imageNewUrl);		
		System.out.println("修改成功！！");
	}
	//通过图片原始URL路径找到相关信息查询一条数据
	public Image selectOneImageToId(String imgUrl){
		return imageMapper.selectOneImageToId(imgUrl);
	}
	/**
	 * 上传图片到七牛云，并获取七牛云的URL路径
	 */
	public String imageQiNiuUrl(String url, String imgName, String bucket) throws IOException {
		String qiNiuName="";
		boolean falg = false;
		String newUrl="";
		//密钥配置
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		NetUploadDemo netUpload = new NetUploadDemo(auth);
		qiNiuName = "";
		DefaultPutRet dfaultPutRet = netUpload.fetch(url, bucket,imgName);//存数据库
		if(null!=dfaultPutRet){
			qiNiuName=dfaultPutRet.hash;
			System.out.println(qiNiuName);
			falg=true;
		}
		if(falg){
			System.out.println("CheckUtil-----qiNiuName"+qiNiuName);
			newUrl=ReqParams.domain+qiNiuName;
		}
		return newUrl;
	}
	public static void main(String[] args) {
		try {
			String str=new ImageUploadServiceImpl().imageQiNiuUrl("http://img3.duitang.com/uploads/item/201605/18/20160518141838_Hj8EK.jpeg", null, ReqParams.bucket);
		    System.out.println(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
